package com.gnerv.pabu.basic.core.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gnerv.pabu.basic.core.dto.PermissionDTO;
import com.gnerv.pabu.basic.core.dto.PermissionSaveDTO;
import com.gnerv.pabu.basic.core.dto.PermissionSearchDTO;
import com.gnerv.pabu.basic.core.entity.Permission;
import com.gnerv.pabu.basic.core.mapper.PermissionMapper;
import com.gnerv.pabu.basic.core.service.IPermissionService;
import com.gnerv.pabu.basic.core.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * <p>
 * 基础平台-权限表 服务实现类
 * </p>
 *
 * @author Gnerv LiGen
 * @since 2019-10-10
 */
@Slf4j
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    PermissionMapper permissionMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean savePermission(PermissionSaveDTO permissionSaveDTO) {
        if (StringUtils.isEmpty(permissionSaveDTO.getUkId())) {
            this.createPermission(permissionSaveDTO);
        } else {
            this.updatePermission(permissionSaveDTO);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createPermission(PermissionSaveDTO permissionSaveDTO) {
        Permission permission = permissionSaveDTO.convert();
        permission.setUkId(UUIDUtils.getLower());
        permissionMapper.insertPermission(permission);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByPermissionId(String permissionId) {
        permissionMapper.deleteById(permissionId);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePermission(PermissionSaveDTO permissionSaveDTO) {
        Permission permission = permissionSaveDTO.convert();
        permissionMapper.updateById(permission);
        return true;
    }

    @Override
    public PermissionDTO selectPermission(String permissionId) {
        PermissionDTO permission = permissionMapper.selectPermission(permissionId);
        return permission;
    }

    @Override
    public Page<PermissionDTO> listPermission(PermissionSearchDTO permissionSearchDTO, Long current, Long size) {
        Page<PermissionDTO> permissions = permissionMapper.listPermission(new Page(current, size), permissionSearchDTO);
        return permissions;
    }

    @Override
    public boolean updatePermissionStatus(String permissionId, Integer status) {
        permissionMapper.updatePermissionStatus(permissionId, status);
        return true;
    }
}
